<?php

namespace Biz\Services\Notify;

use Lumen\Logger\Logger;
use Biz\Models\Notify\Notify;
use Illuminate\Support\Facades\DB;
use Biz\Constants\Pay\PayConstants;
use Biz\Models\Notify\NotifyPayEase;
use Biz\Services\Passport\ClientService;
use Biz\Constants\Notify\NotifyConstants;
use Lumen\Core\Exceptions\BusinessException;
use Biz\Repositories\Notify\NotifyPayEaseRepository;

/**
 * NotifyPayEaseService.
 *
 * @license [http://www.85do.com] [杭州永奥网络科技有限公司]
 * @copyright Copyright (c) 2018-2026 Hangzhou Yongao Technology Co., Ltd. All rights reserved.
 */
class NotifyPayEaseService
{
    /**
     * @var \Lumen\Repository\Contracts\RepositoryContract
     */
    protected $repository;

    /**
     * @var ClientService
     */
    protected $clientService;

    /**
     * RepositoryController constructor.
     *
     * @param NotifyPayEaseRepository $repository
     * @param NotifyService           $notifyService
     */
    public function __construct(NotifyPayEaseRepository $repository, NotifyService $notifyService)
    {
        $this->repository         = $repository;
        $this->notifyService      = $notifyService;
    }

    /**
     * Create.
     *
     * @param array $data
     *
     * @throws \Exception
     *
     * @return NotifyPayEase
     */
    public function create(array $data): NotifyPayEase
    {
        // type default
        if (! isset($data['method'])) {
            throw new BusinessException('处理方式不可为空');
        }

        // 1) Start Transaction
        DB::beginTransaction();
        try {
            // 创建通知主记录
            $notifyData = [
                'type'   => NotifyConstants::TYPE_SITE,
                'gateway'=> PayConstants::GATEWAY_PAY_EASE,
                'driver' => PayConstants::DRIVER_PAY_EASE_ONLINE_PAY,
            ];
            /** @var Notify $notify */
            $notify           = $this->notifyService->create($notifyData);

            // 创建易支付通知记录
            /* @var NotifyPayEase $notifyPayEase */
            $data['notify_id'] = $notify->id;
            $notifyPayEase     = $this->repository->create($data);
            if (! $notifyPayEase) {
                throw new BusinessException('通知创建失败');
            }

            // 2) Commit Transaction
            DB::commit();
        } catch (\Exception $e) {
            // 3) Rollback Transaction
            DB::rollback();
            // 4) Log Transaction
            Logger::error(__CLASS__, __FUNCTION__, $e);
            // 5) Throw Exception
            throw $e;
        }

        return $notifyPayEase;
    }
}
